from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q, ProtectedError
from django.shortcuts import render
from django.db import IntegrityError

from clazz.models import Clazz
from utils.customerutils import CustomerUtils
from utils.responsestatus import ResponseStatus
from utils import responsedata


# Create your views here.


# 搜索分页
def clazz_page(request):
    # current_page size 接收分页参数
    if request.method == 'POST':
        # {'page': 1, 'size': 5，headteacher,class_room,class_state}
        form_data = CustomerUtils.get_request_data(request)
        print(form_data)
        # 空条件
        condition = Q()
        # 动态条件 存在就拼接
        if form_data.get('headteacher').strip():
            # 复杂查询用Q 大小写不敏感icontains
            condition &= Q(headteacher__icontains=form_data['headteacher'])
        if form_data.get('class_room').strip():
            condition &= Q(class_room__icontains=form_data['class_room'])
        if form_data.get('class_state') != '':
            condition &= Q(class_state=form_data['class_state'])

        # 分页处理 传回去total条数 tableData数据
        clazz_list = Clazz.objects.filter(condition).order_by('-id')
        # 获取分页对象
        paginator = Paginator(clazz_list, form_data.get('size', 5))
        # 获取数据总条数
        total = paginator.count
        try:
            # 当前页对象
            current_page = paginator.page(form_data.get('page', 1))
        except EmptyPage as e:
            current_page = paginator.page(1)
        # 当前页数据 [{},{},{}]
        table_data = current_page.object_list


        clazzs = []
        for clazz in table_data:
            clazzs.append({
                'id': clazz.id,
                'class_name': clazz.class_name,
                'class_room': clazz.class_room,
                'class_state': clazz.class_state,
                'student_number': clazz.student_number,
                'headteacher': clazz.headteacher,
                'class_start': clazz.class_start.strftime('%Y-%m-%d'),

            })
        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'data': {
                'total': total,
                'tableData': clazzs
            }
        }

        return CustomerUtils.response_json(response)

def clazz_state(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        Clazz.objects.filter(id=form_data.get('id')).update(class_state=form_data.get('state'))
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def clazz_one(request, id):
    clazz = Clazz.objects.filter(id=id).first()
    print(clazz)
    response = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data' : {
            'clazz': {
                'id': clazz.id,
                'class_name': clazz.class_name,
                'class_room': clazz.class_room,
                'class_state': clazz.class_state,
                'student_number': clazz.student_number,
                'headteacher': clazz.headteacher,
                'class_start': clazz.class_start.strftime('%Y-%m-%d'),
            }
        }
    }
    return CustomerUtils.response_json(response)

def clazz_insert_edit(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        clazz_id = form_data.get('id')
        try:
            if clazz_id is not None:
                # 更新操作
                Clazz.objects.filter(id=clazz_id).update(**form_data)
            else:
                Clazz(**form_data).save()
        except IntegrityError as e:
            response = responsedata.BUSINESS_ERROR_DATA
            response['message'] = str(e)
            return CustomerUtils.response_json(response)
        else:
            return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)

def clazz_remove(request, id):
    try:
        Clazz.objects.filter(id=id).delete()
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)
    except ProtectedError as e:
        response = {
            'code': ResponseStatus.BUSINESS_ERROR,
            'message': '班级被占用，不能删除！'
        }
        return CustomerUtils.response_json(response)


def clazz_list(request):
    clazz_list = Clazz.objects.all()
    clazzs = []
    for clazz in clazz_list:
        clazzs.append({
            'id': clazz.id,
            'class_name': clazz.class_name,
        })
    resp = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'clazzList': clazzs
        }
    }
    return CustomerUtils.response_json(resp)